package com.transcargo.request;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.transcargo.action.ServletParametersException;
import com.transcargo.action.ServletValidationException;
import com.transcargo.db.dbException;
import com.transcargo.rpc.RPCOutput;
import com.transcargo.users.Transport;
import com.transcargo.users.TransportNotFoundException;

public class GetTransportRequest extends AuthRequest
{
	private String tid = "";
	private String xml = "";
	
    private void servletGetValues(HttpServletRequest request) throws ServletParametersException, ServletException {
		tid = request.getParameter("tid");
		if (tid == null) tid = "";
    }
    private void servletValidateValues() throws ServletValidationException {
    	if (Integer.parseInt(tid) == 0 || tid.length() == 0) throw new ServletValidationException("Empty tid");
    }
    private void servletExecuteRequest() throws ServletRequestException {
		Transport tr;
		try {
			tr = new Transport(Integer.parseInt(tid), User_Id, dbase);
		} catch (NumberFormatException e) {
			throw new ServletRequestException();
		} catch (dbException e) {
			throw new ServletRequestException();
		} catch (TransportNotFoundException e) {
			throw new ServletRequestException();
		}
		xml =  RPCOutput.generate(tr);
    }
    public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        PrintWriter out = null;
		try {
            out = response.getWriter();
            servletGetValues(request);
            servletValidateValues();
            servletExecuteRequest();
            out.println(xml);
	    } catch (ServletParametersException e) {
           sendRedirect(response, "index.jsp");
        }  catch (ServletValidationException e) {
            sendError(response, new Exception(e.getMessage()));
        }  catch (ServletRequestException e) {
            String xml =  RPCOutput.generate(false);
            out.println(xml);
        }  catch (IOException e) {
            System.out.println("IOException: " + e.getMessage());
        }
    }
}